<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Storage;
use DB;

/**
 * Class ShanghuType
 * @package App
 */
class ShanghuType extends Model
{
    public $timestamps = false;
    protected $table = 's_shanghu_type';

    /**
     * 类型列表
     * @return \Illuminate\Support\Collection
     */
    static function Types()
    {
        return  ShanghuType::select('store_type')->get();
    }


    /**
     * 添加类型
     * @param $request
     * @return array
     */
    static function ShopTypePublish($request)
    {
        $type = new ShanghuType();
        $type->store_type = $request->store_type;
        $type->weight = $request->weight;
        $type->pic = Storage::url(Postings::OssUpdate($request->pic));
        $type->act = Storage::url(Postings::OssUpdate($request->act));
        $type->pin_pic = Storage::url(Postings::OssUpdate($request->pin_pic));

        if (!$type->save()) {
            return ['status' => 2, 'message' => '失败'];
        }

        return ['status' => 1, 'message' => '成功'];
    }

    /**
     * 修改店铺类型
     * @param $request
     * @param $id
     * @return array
     * @throws \Exception
     */
    static function ShopTypeModify($request, $id)
    {
        DB::beginTransaction();

        $type =  ShanghuType::find($id);
        $store_type = $type->store_type;
        //修改商铺类型名
        if ($request->store_type !== $store_type) {
            if (ShopInfo::where('store_type', $store_type)->exists()) {
                if (!ShopInfo::where('store_type', $store_type)->update([
                    'store_type' => $request->store_type
                ])) {
                    DB::rollBack();

                    return ['status' => 2, 'message' => '失败'];
                }
            }

        }
        $type->store_type = $request->store_type;
        $type->weight = $request->weight;
        if ($request->has('pic')) {
            $type->pic = Storage::url(Postings::OssUpdate($request->pic));
        }
        if ($request->has('act')) {
            $type->act = Storage::url(Postings::OssUpdate($request->act));
        }
        if ($request->has('pin_pic')) {
            $pin_pic = Storage::url(Postings::OssUpdate($request->pin_pic));
            $type->pin_pic = $pin_pic;
            //修改商户的大头针
            if (ShopInfo::where('store_type', $store_type)->exists()) {
                if (!ShopInfo::where('store_type', $store_type)->update([
                    'pin_pic' => $pin_pic
                ])) {
                    DB::rollBack();

                    return ['status' => 2, 'message' => '失败'];
                }
            }
        }

        if (!$type->save()) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }

        DB::commit();

        return ['status' => 1, 'message' => '成功'];
    }
}
